package es.esa.integral;

/**
 * Created by esalazar on 4/28/14.
 */


public  class Position {
    double ra;
    double dec;
    /**
     * Transformation Matrix for Equatorial to Galactic coordinate conversions.
     */
    private static Matrix s_cMatrix = new Matrix(new double[][] {
            {-0.0548755604, 0.4941094279,-0.8676661490},
            {-0.8734370902,-0.4448296300,-0.1980763734},
            {-0.4838350155, 0.7469822445, 0.4559837762}
    });
    public static final int SCALE = 7;

    public Position(double l, double b) {
        this.ra = galactic2Equatorial(l, b)[0];
        this.dec = galactic2Equatorial(l, b)[1];
    }


    public static double round(double value, int scale) {
        double m = Math.pow(10,scale);
        double tmp = value * m;
        tmp = Math.round(tmp);
        double res = tmp/m;
        return res;
    }
    public static double[] galactic2Equatorial(double l, double b) {
        double[] gVector = new double[3];
        double[] eVector;

// Create galactic vector
        gVector[0] = Math.cos(Math.toRadians(l)) * Math.cos(Math.toRadians(b));
        gVector[1] = Math.sin(Math.toRadians(l)) * Math.cos(Math.toRadians(b));
        gVector[2] = Math.sin(Math.toRadians(b));

// The matrix defines tranformation from Equa to Galactic coords.
// Hence we need the INVERSE tranformation.
        eVector = s_cMatrix.inverseTransform(gVector);

        double ra = Math.toDegrees(Math.atan2(eVector[1], eVector[0]));
        if (ra < 0.0) {
            ra = 360.0 + ra;
        }
        double dec = Math.toDegrees(Math.asin(eVector[2]));

        ra = round(ra,SCALE);
        if(ra >= 360.0) ra = 0.0;
        dec = round(dec,SCALE);
        return new double[] {ra, dec};
    }
}
